import zipimport
django = zipimport.zipimporter('../django_dev.zip').load_module('django')
from django.utils import simplejson as json
import csv

def process_major(f='majors.json'):
  obj = json.load(open(f, 'r'))
  writer = csv.writer(open('majors.csv', 'w'))
  writer.writerow(['key', 'long_name', 'short_name'])
  for (shortname, longname) in obj:
    writer.writerow([shortname, longname, shortname])

def process_class(f='classes.json'):
  obj = json.load(open(f, 'r'))
  writer = csv.writer(open('classes.csv', 'w'))
  writer.writerow(['key', 'long_name', 'major', 'short_name'])
  for major_short, class_short, class_long, url in obj:
    writer.writerow(['%s %s' % (major_short, class_short), class_long, major_short, class_short])

def process_section(f='sections.json'):
  obj = json.load(open(f, 'r'))
  writer = csv.writer(open('sections.csv', 'w'))
  writer.writerow(['key', 'classes', 'type', 'num', 'ccn', 'books_url',
      'instructor', 'last_updated', 'location', 'primary', 'primary_lec',
      'time'])
  for (major_short, class_short, s_type, s_num, s_parent, time, loc, inst,
      ccn, last_updated, books, pri) in obj:
    class_key = '%s %s' % (major_short, class_short)
    try:
      if ccn:
        ccn = int(ccn.split(' ')[0])
      else:
        ccn = None
    except Exception:
      ccn = None
    if not pri:
      parent = '%s %s - %s %s' % (major_short, class_short, s_parent[0],
          s_parent[1])
    else:
      parent = ''
    writer.writerow(['%s %s - %s %s' % (major_short, class_short, s_type, s_num),
        '%s %s' % (major_short, class_short), s_type, s_num, ccn, books,
        inst, last_updated, loc, str(pri).upper(),
        parent, time])
        
process_major()
process_class()
process_section()